#!/usr/bin/env bash
# gogs

if [[ -z "${c_gogs}" ]]; then
    f_info 'gogs: not install';
    echo > /dev/null;  return;
fi;

# install
dir='/home/git';  own='git:git';  isMsg='';
if [[ -d "${dir}/gogs" ]]; then f_info 'gogs: has install';
else
    f_wait 'gogs: install';  isMsg='1';
    tar zxf "${RUN}/file/gogs/gogs.tgz" -C "${dir}" || f_fail 'gogs: tar zxf';
    f_mode "${dir}/gogs" '-' '-' "${own}";
fi;

# config
mkdir -p "${dir}/data" || f_fail 'gogs: mkdir data';
mkdir -p "${dir}/repos" || f_fail 'gogs: mkdir repos';
mkdir -p "${dir}/logs" || f_fail 'gogs: mkdir logs';
mkdir -p "${dir}/.ssh" || f_fail 'gogs: mkdir .ssh';
f_mode "${dir}/data" '-' '-' "${own}"
f_mode "${dir}/repos" '-' '-' "${own}"
f_mode "${dir}/logs" '-' '-' "${own}"
f_mode "${dir}/.ssh" '700' '-' "${own}"
if [[ ! -f "${dir}/data/sqlite.db" ]]; then
    isMsg='1';
    f_copy "${RUN}/file/gogs/sqlite.db" "${dir}/data/sqlite.db" '-' '-' "${own}";
fi;
if [[ -L "${dir}/.gitconfig" ]]; then
    isMsg='1';
    f_copy "${RUN}/file/gogs/gitconfig" "${dir}/.gitconfig" "${own}";
fi;
if [[ ! -f "${dir}/app.ini" ]]; then
    ssl='';  [[ -n "${c_gogs_ssl}" ]] && ssl='s';  isMsg='1';
    sed "s/{NAME}/${c_gogs_name}/g" "${RUN}/file/gogs/app.ini" \
        | sed "s/{DOMAIN}/${c_gogs_domain}/g" | sed "s/{SSL}/${ssl}/g" \
        > "${dir}/app.ini" || f_fail 'gogs: save app.ini';
    f_mode "${dir}/app.ini" '700' '-' "${own}";
fi;

# nginx & httpd
cfg='/home/www/conf'; ngx="${cfg}/@ngx"; apc="${cfg}/@apc";
if [[ ! -d "${ngx}/demo"  ]]; then
    if [[ ! -d "${cfg}" ]]; then not="${cfg}";
    elif [[ ! -d "${ngx}" ]]; then not="${ngx}";
    else not="${ngx}/demo"; fi;
    mkdir -p "${ngx}/demo" || f_fail 'gogs: mkdir ngx conf demo';
    f_mode "${not}" '755' '-' 'www:www';
fi;
sed "s/{DOMAIN}/${c_gogs_domain}/g" "${RUN}/file/gogs/ngx.conf" \
    > "${ngx}/demo/gogs.conf" || f_fail 'gogs: save ngx.conf';
f_mode "${ngx}/demo/gogs.conf" '-' '-' 'www:www';
if [[ ! -d "${apc}/demo"  ]]; then
    if [[ ! -d "${cfg}" ]]; then not="${cfg}";
    elif [[ ! -d "${apc}" ]]; then not="${apc}";
    else not="${apc}/demo"; fi;
    mkdir -p "${apc}/demo" || f_fail 'gogs: mkdir apc conf demo';
    f_mode "${not}" '755' '-' 'www:www';
fi;
sed "s/{DOMAIN}/${c_gogs_domain}/g" "${RUN}/file/gogs/apc.conf" \
    > "${apc}/demo/gogs.conf" || f_fail 'gogs: save apc.conf';
f_mode "${apc}/demo/gogs.conf" '-' '-' 'www:www';

# auto & start
f_link "${DIR}/serv/gogs.service" '/usr/lib/systemd/system/gogs.service';
f_auto 'gogs' 'gogs' 1;
systemctl restart gogs || f_fail 'gogs: restart srv';

[[ -n "${isMsg}" ]] && MSG="${MSG}\n  gogs: 默认账户(在web可改)adm,密码123456";
echo > /dev/null;
